<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="师傅姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入师傅姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="level">
        <el-select clearable v-model="queryParams.level" placeholder="请选择类型"  style="width: 240px">
                    <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
         </el-select>
          <!-- <el-tree-select
              v-model=""
              :data="levelList"
              :render-after-expand="false"
              :props="{ label: 'name',value:'id' }"
              style="width: 240px"
            /> -->
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['master:master:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['master:master:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['master:master:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['master:master:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="masterList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="师傅姓名" align="center" prop="nickName" />
      <el-table-column label="师傅账号" align="center" prop="userName" />
      <el-table-column label="师傅电话" align="center" prop="phonenumber" />
      <el-table-column label="服务次数" align="center" prop="serviceNum" />
      <el-table-column label="发布数量" align="center" prop="publishNum" />
      <el-table-column label="佣金余额" align="center" prop="balance" />
      <el-table-column label="保证金余额" align="center" prop="bond" />
      <el-table-column label="级别" align="center" prop="levelName" />
      <el-table-column label="描述" align="center" prop="memo" >
        <template #default="scope">
          <!-- 小于12位默认展示 -->
          <div v-if="scope.row.memo != null && scope.row.memo.length <= 10">
            {{ scope.row.memo }}
          </div>
          <!-- 大于12为只展示12位 -->
          <el-tooltip
            v-if="scope.row.memo != null && scope.row.memo.length > 10"
            popper-class="testtooltip"
            :content="scope.row.memo"
            placement="top-start"
          >
            <div>{{ scope.row.memo.slice(0, 10) }}...</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建名称" align="center" prop="createName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!--  <el-table-column label="更新人" align="center" prop="updateUser" />
      <el-table-column label="更新名称" align="center" prop="updateName" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
            <el-tooltip content="修改" placement="top" >
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="余额变更记录" placement="top" >
              <el-button link type="primary" icon="CircleCheck" @click="handleOrder(scope.row)" v-hasPermi="['system:user:projectList']"></el-button>
            </el-tooltip>
            <el-tooltip content="重置密码" placement="top">
                <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
            </el-tooltip>
            <el-tooltip content="发布列表" placement="top" >
              <el-button link type="primary" icon="CircleCheck" @click="handleProject(scope.row)" v-hasPermi="['system:user:projectList']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改保证金" placement="top" >
              <el-button link type="primary" icon="Edit" @click="handleUpdateBond(scope.row)" v-hasPermi="['system:user:editBond']"></el-button>
            </el-tooltip>
            <el-tooltip content="保证金记录" placement="top" >
              <el-button link type="primary" icon="CircleCheck" @click="handleBond(scope.row)" v-hasPermi="['system:user:bondList']"></el-button>
            </el-tooltip>
        </template>

        <!-- <template #default="scope">
          <router-link :to="{path: '/clothing/'+scope.row.id}">发布列表</router-link>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['master:master:edit']"
            >修改</el-button
          >
          <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['master:master:remove']"
            >删除</el-button
          >
        </template> -->
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改师傅信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="masterRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item class="form-item" label="师傅姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入师傅姓名" />
        </el-form-item>
         <el-form-item class="form-item" label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item
          class="form-item"
          label="密码"
          prop="password"
          v-if="title=='添加师傅信息'"
        >
          <el-input v-model="form.password" placeholder="请输入密码" type="password" maxlength="20" show-password />
        </el-form-item>
       
        <!-- <el-form-item class="form-item" label="服务次数" prop="serviceNum">
          <el-input-number v-model="form.serviceNum" :min="1" />
        </el-form-item>
        <el-form-item class="form-item" label="发布数量" prop="publishNum">
          <el-input-number v-model="form.publishNum" :min="1" />
        </el-form-item> -->
        <el-form-item class="form-item" label="师傅等级" prop="level">
          <el-select clearable v-model="form.level" placeholder="请选择类型"  style="width: 240px"  @change="handleTypeChange">
                    <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"  />
         </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="描述" prop="memo">
          <el-input v-model="form.memo" type="textarea" :rows="10" placeholder="请输入描述" />
        </el-form-item>
         <el-form-item class="form-item" label="介绍链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入介绍链接" />
        </el-form-item>
         <el-form-item label="预约及时率">
            <el-input-number v-model="form.reservation" :min="1" />
          </el-form-item>
          <el-form-item  label="预约达成率">
            <el-input-number v-model="form.appoint" :min="1" />
          </el-form-item>
          <el-form-item label="按时完成率">
            <el-input-number v-model="form.completion" :min="1" />
          </el-form-item>
          <el-form-item label="投诉率">
            <el-input-number v-model="form.complaint" :min="1" />
          </el-form-item>
          <el-form-item label="退款率">
            <el-input-number v-model="form.refund" :min="1" />
          </el-form-item>

      </el-form>
          <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
    </el-dialog>

    <el-dialog :title="title" v-model="openBond" width="500px" append-to-body>
      <el-form ref="bondRef" :model="formBond" :rules="rules" label-width="100px">
          <el-form-item prop="money" label="金额">
            <el-input-number v-model="formBond.money" :min="1" />
          </el-form-item>
          <el-form-item prop="type" label="类型">
              <el-radio-group v-model="formBond.type">
                  <el-radio :value="1">增加</el-radio>
                  <el-radio :value="0">减少</el-radio>
              </el-radio-group>
          </el-form-item>
      </el-form>
       <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFormBond">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
    </el-dialog>

    <el-dialog :title="title" v-model="open1" width="500px" append-to-body>
      <el-form ref="masterRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item prop="money" label="预约及时率">
            <el-input-number v-model="form.reservation" :min="1" />
          </el-form-item>
          <el-form-item prop="money" label="预约达成率">
            <el-input-number v-model="form.appoint" :min="1" />
          </el-form-item>
          <el-form-item prop="money" label="按时完成率">
            <el-input-number v-model="form.completion" :min="1" />
          </el-form-item>
          <el-form-item prop="money" label="投诉率">
            <el-input-number v-model="form.complaint" :min="1" />
          </el-form-item>
          <el-form-item prop="money" label="退款率">
            <el-input-number v-model="form.refund" :min="1" />
          </el-form-item>
      </el-form>
       <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFormBond">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
    </el-dialog>
  </div>
</template>

<script setup name="Master">
import {
  listMaster,
  getMaster,
  delMaster,
  addMaster,
  updateMaster,
} from "@/api/main/master";
import {resetUserPwd} from "@/api/system/user";
import {updateBond} from "@/api/main/bond";
import { listLevel } from "@/api/main/level";
import { useRouter } from "vue-router";
// import func from "../../../../vue-temp/vue-editor-bridge";

const { proxy } = getCurrentInstance();
const router=useRouter();
const masterList = ref([]);
const open = ref(false);
const openBond=ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const levelList=ref([]);
const bond=ref(0);

const data = reactive({
  form: {},
  formBond:{},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceNum: null,
    publishNum: null,
    level: null,
    memo: null,
    status: null,
    createUser: null,
    createName: null,
    updateUser: null,
    updateName: null,
    nickName: null,
    userName: null,
    phonenumber: null,
    password: null,
  },
  rules: {
    userName: [{ required: true, message: "师傅名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
    nickName: [{ required: true, message: "师傅昵称不能为空", trigger: "blur" }],
    password: [{ required: true, message: "师傅密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }],
    phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
    memo: [{ required: true, message: "描述不能为空", trigger: "change" }],
    level: [{ required: true, message: "等级不能为空", trigger: "change" }],
    type: [{ required: true, message: "类型不能为空", trigger: "change" }],
    money: [{ required: true, message: "金额不能为空", trigger: "change" }],
    link: [{ required: true, message: "介绍链接不能为空", trigger: "change" }],
  },
});

const { queryParams, form,formBond, rules } = toRefs(data);

/** 查询师傅信息列表 */
function getList() {
  loading.value = true;
  listMaster(queryParams.value).then((response) => {
    masterList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function getLevelList(){
  listLevel().then(res=>{
    levelList.value=res.data;
  })
}
function handleChange(data){
  const type= levelList.value.filter((temp)=>temp.id===data);
     if (type.length>0) {
        form.value.levelName = type[0].name;
      } else {
        form.value.levelName = null;
      }
}
// 取消按钮
function cancel() {
  open.value = false;
  openBond.value = false;
  reset();
  resetBond();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    serviceNum: null,
    publishNum: null,
    level: null,
    memo: null,
    status: null,
    delFlag: null,
    createUser: null,
    createName: null,
    createTime: null,
    updateUser: null,
    updateName: null,
    updateTime: null,
    nickName: null,
    userName: null,
    phonenumber: null,
    password: null,
    sort:null
  };
  proxy.resetForm("masterRef");
}

function resetBond(){
  formBond.value = {
    id: null,
    money: null,
    type: null,
    masterId: null,
    masterName: null
  };
  bond.value=0
proxy.resetForm("bondRef");
}
 function handleTypeChange(data){
  console.log(123123)
     const type= levelList.value.filter((temp)=>temp.id===data);
     if (type.length>0) {
        form.value.levelName = type[0].name;
        form.value.sort = type[0].sort;
      } else {
        form.value.levelName = null;
      }
  }
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加师傅信息";
}
/** 修改保证金 */
function handleUpdateBond(row){
    formBond.value.masterId=row.userId
    formBond.value.masterName=row.nickName
    bond.value=row.bond
    openBond.value=true;
    title.value = "修改保证金";
   
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getMaster(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改师傅信息";
  });
}
//跳转案例列表
function handleProject(row){
  router.push({path: '/clothing/index/'+row.id});
}
//跳转保证金列表
function handleBond(row){
  router.push({path: '/bond/'+row.id});
}
function handleOrder(row){
  router.push({path: '/cashRecord/'+row.id});
}
function submitFormBond(){
  proxy.$refs["bondRef"].validate((valid) => {
    if (valid) {
      if(formBond.value.money>bond.value&&formBond.value.type==0){
        return proxy.$modal.msgError("保证金余额不足");
      }
      updateBond(formBond.value).then((response) => {
              proxy.$modal.msgSuccess("修改成功");
              openBond.value = false;
              resetBond();
              getList();
            }); 
    }
  });
}
/** 提交按钮 */
function submitForm() {

  proxy.$refs["masterRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateMaster(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.userName=form.value.phonenumber
        addMaster(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字符：< > \" ' \\\ |"
      }
    },
  }).then(({ value }) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
    });
  }).catch(() => {});
};
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除师傅信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delMaster(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "master/master/export",
    {
      ...queryParams.value,
    },
    `master_${new Date().getTime()}.xlsx`
  );
}

getList();
getLevelList();
</script>

<style>
/* 添加的CSS样式 */
.form-item {
  margin-bottom: 24px; /* 或其他你想要的间隔 */
}
.dialog-footer {
  text-align: right;
}
</style>